package com.msmall.community.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import com.msmall.community.common.Configuration;

/**
 * 
 * @author zhzy
 *
 */
public class FilterCharsUtil {
	
	/**
	 * 获得系统设置的非法字符
	 * @return
	 */
	public static String getFilterChars(){
		try{
			return Configuration.getValue(Configuration.SYSTEM_FILTER_CHARS);
		}catch(Exception e){
			return "";
		}
	}
	
	/**
	 * 坚持txt中是否存在非法字符
	 * @param txt
	 * @return
	 */
	public static boolean containsFilterChars(String txt){
		if (StringUtils.isNotBlank(getFilterChars())) {
			String[] words = getFilterChars().split(";");
			for (int i = 0; i < words.length; i++) {
				Pattern p = Pattern.compile(words[i]);
				Matcher m = p.matcher(txt);
				if (m.find()) {
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * 使用特定字符替换所以的非法字符
	 * @param txt 包含非法字符的内容
	 * @param replacement 替换非法字符的字符， 默认**
	 * @return
	 */
	public static String replaceAllFilterChars(String txt, String replacement){
		if(StringUtils.isBlank(replacement))
			replacement = "**";
		if (StringUtils.isNotBlank(getFilterChars())) {
			String[] words = getFilterChars().split(";");
			for (int i = 0; i < words.length; i++) {
				txt = txt.replaceAll(words[i], replacement);
			}
		}
		return txt;
	}
	/*
	 public static String getFilterChars(){
	 	return "法轮功;江泽民;好人";
	 }
	 */
	public static void main(String args[]){
		String txt = "阿隆索的发来看警方法轮功江泽民；好人xxe哦好的阿的剑法 甲胺磷";
		System.out.println(FilterCharsUtil.containsFilterChars(txt));
		System.out.println(FilterCharsUtil.replaceAllFilterChars(txt, "##"));
	}
	
}
